import { logout, getInfo } from '@/api/login.js'
import { getToken, setToken, removeToken } from '@/utils/auth.js'
import { getRequestInfoList } from '@/api/IM/loopAjax.js'
import { isEmpty } from '@/utils/fromValidate.js'
let lock = false
const user = {
  state: {
    token: getToken(),
    // 判断是否登录
    isLogin: false,
    // 用户信息
    userInfo: {},
    // 请求消息
    myRequestInfos: [],
    // 同意消息
    buddyBy: [],
    // 拒绝消息
    refusal: [],
  },
  mutations: {
    toggleIsLogin(state, isLogin) {
      state.isLogin = typeof isLogin === 'undefined' ? !state.isLogin : isLogin
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_AVATAR: (state, avatar) => {
      state.userInfo.avatar = avatar
    },
    SET_USERINFO: (state, user) => {
      state.userInfo = user
    },
    UPDATE_NEW_FIREND: (state, res) => {
      // 如果为空全部赋值undefined
      if (isEmpty(res.myRequestInfos)) {
        state.myRequestInfos = undefined
      } else {
        state.myRequestInfos = res.myRequestInfos
      }

      if (isEmpty(res.buddyBy)) {
        state.buddyBy = undefined
      } else {
        state.buddyBy = res.buddyBy
      }

      if (isEmpty(res.refusal)) {
        state.refusal = undefined
      } else {
        state.refusal = res.refusal
      }
    },
  },
  actions: {
    // 登录
    Login({ dispatch, commit }, res) {
      setToken(res.token)
      commit('SET_TOKEN', res.token)
      dispatch('GetInfo')
    },
    // 获取用户信息
    GetInfo({ dispatch, commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          console.log(res);
          let user = res.user
          const avatar = user.avatar == "" ? require("@/assets/image/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
          user.avatar = avatar
          commit('SET_USERINFO', user)
          commit('toggleIsLogin', true)
          dispatch('loopAjax')
          // commit('UP_ADDRESS')
          // dispatch('initWebsocket')
          resolve(res)
        }).catch(error => {
          dispatch('FedLogOut')
          reject(error)
        })
      })
    },
    // ajax轮询
    loopAjax({ commit, state }) {
      if (state.isLogin) {
        let timer = setInterval(async () => {
          if (!lock) {
            lock = true;
            const res = await getRequestInfoList(state.userInfo.userId)
            if (res.code != 200) {
              console.log("接口错误处理", res.msg);
              lock = false;
              // window.clearInterval(timer);
              return;
            }
            commit('UPDATE_NEW_FIREND', res)
            lock = false;
          }
        }, 1000);
      }
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          // commit('SET_ROLES', [])
          // commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
  }
}

export default user